package com.yeyv.net.Web.Control.Security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yeyv.net.UsefulEntity.Resp;
import com.yeyv.net.Web.Entity.GameAuthEntity;
import com.yeyv.net.Web.Entity.GameEntity;
import com.yeyv.net.Web.Service.GameAuthService;
import com.yeyv.net.Web.Service.GameService;
import com.yeyv.net.Web.Utils.SendMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/gameAuth")
public class GameAuthController {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private GameAuthService gameAuthService;

    @Autowired
    private GameService gameService;

    @Autowired
    private SendMail mail;

    @PostMapping("/authList")
    private Resp<List<HashMap<String, String>>> authList() {
        return Resp.success(gameAuthService.authList(1, 2));
    }

    @PostMapping("/authed")
    private Resp<String> authed(int id, String password) {
        GameAuthEntity authEntity = gameAuthService.getById(id);
        GameEntity game = gameService.getOne(new LambdaQueryWrapper<GameEntity>().eq(GameEntity::getKeyword, authEntity.getGame()));
        StringBuffer buff = new StringBuffer("若雨.NET(www.ruoyv.com) : ").append("您的游戏 :《")
                .append(game.getTitle())
                .append("》授权");
        String title = "若雨.NET 游戏授权完成";
        if (authEntity.getAuthed() == 1) {
            buff.append("已完成，验证码/授权码/密码 为:").append(password);
            authEntity.setAuthed(2);
            authEntity.setPassword(StringUtils.isBlank(password) ? authEntity.getPassword() : password);
        } else {
            title = "若雨.NET 游戏授权码重置/重发";
            buff.append("已重置/重发，验证码/授权码/密码 为:")
                    .append(password);
            authEntity.setPassword(StringUtils.isBlank(password) ? authEntity.getPassword() : password);
        }
        gameAuthService.updateById(authEntity);
        if (StringUtils.isNotBlank(authEntity.getMail()))
            mail.send(authEntity.getMail(), title, buff.toString());
        return Resp.success(buff.toString());
    }
}
